package com.demo.sse.controller;

import com.demo.sse.model.ServerMessage;
import com.demo.sse.service.SseService;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import java.util.UUID;


@RestController
@RequestMapping("/api/sse")
@CrossOrigin(origins = "*") // Enable CORS for demo purposes
public class EnhancedSseController {
    private final ExecutorService asyncExecutor = 
        Executors.newCachedThreadPool();

    @GetMapping(value = "/stream2", produces = "text/event-stream")
    public SseEmitter streamData() {
        SseEmitter emitter = new SseEmitter(120_000L); // 2分钟超时
        int counterId = 0;

        asyncExecutor.execute(() -> {
            try {
                int count = 0;
                while (!Thread.currentThread().isInterrupted()) {
                    emitter.send(generateData(count++));  // 业务数据生成
                    TimeUnit.SECONDS.sleep(2);     // 精准间隔控制
                }
            } catch (Exception e) {
                emitter.completeWithError(e);
            }
        });
        
        return emitter; 
    }

    private ServerMessage generateData(int count) {
        // 使用四个参数的构造函数: id, content, timestamp, counterId
        return new ServerMessage(
            UUID.randomUUID().toString(),
            "Hello, SSE! Count:" + count,
            System.currentTimeMillis(),
            count % 5 // 使用模5的结果作为 counterId，确保在0-4之间循环
        );
    }
}